<template>
  <!-- 上传 -->
  <div class="w-full flex justify-center items-center flex-col min-h-[90px]">
    <van-uploader
      v-if="edit"
      v-model="fileList"
      :preview-image="false"
      :reupload="true"
      :after-read="successFile"
    >
      <div class="w-[118px]">
        <van-button color="#EF6800" plain block style="height: 30px">上传文件</van-button>
      </div>
    </van-uploader>
    <div class="bg-white pt-[15px] px-[15px]">
      <div class="mb-[30px] flex items-center" v-for="item in uploadList">
        <van-image
          width="24"
          height="24"
          :src="
            str == 'doc' || str == 'docx'
              ? getAssetsFile('insure/word.png')
              : str == 'xls' || str == 'xlsx'
              ? getAssetsFile('insure/exc.png')
              : str == 'pdf'
              ? getAssetsFile('insure/pdf.png')
              : ''
          "
        />
        <div class="ml-[10px] text-[10px]">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, inject, defineProps } from "vue";
import getAssetsFile from "@/utils/getImageurl.ts";
import OSS from "ali-oss";
defineProps({
  edit: { type: Boolean },
});
const fileList = ref([] as any[]);
const global = inject<any>("global");
const uploadList = ref([] as any[]);
const str = ref(""); //上传文件的类型
//上传成功
const successFile = (file: object, _: object) => {
  httpRequest(file);
};
//上传照片
const httpRequest = (v: any) => {
  //index 0是营业执照，1是身份证正面 2是反面

  let e = v.file;

  let client = new OSS({
    region: global.region,
    //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
    accessKeyId: global.accessKeyId,
    accessKeySecret: global.accessKeySecret,
    bucket: global.bucket,
  });
  //获取当前时间

  let filename = e["name"];

  let res_file = e;

  async function put() {
    try {
      //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
      await client
        .multipartUpload(filename, res_file, {
          progress: () => {
            // console.log("上传进度：" + progre);
            //console.log(percentage); // 上传文件进度
          },
        })
        .then(async (res: any) => {
          let param = {
            name: res.name,
            url: global.oss_url + res.name,
          };
          uploadList.value.push(param);
          strFun(res);
        })
        .catch((_: any) => {
          //return that.toast(0, "上传失败");
        });
    } catch (e) {}
  }

  put();
};
//获取上传文件的格式
const strFun = (res: any) => {
  let index = res.name.indexOf("."); //点的下标
  let len = res.name.length;
  str.value = res.name.slice(index + 1, len);
};
defineExpose({
  uploadList,
});
</script>
<style scoped></style>
